#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest/doctest.h"

#include "../aidb.hpp"
#include "klib/utils.hpp"
#include "klib/net.hpp"
#include "klib/log.hpp"
#include <map>

using namespace klib;
using namespace ai;

TEST_CASE("aidb") {
    log::set_level(log::level_t::debug);
    std::string filename("1.aidb");
    std::string pass("password");
    rand_t<aidb_key_t> rand;
    aidb_key_t key;
    std::map<aidb_key_t, std::string> ids;

    std::remove(filename.c_str());

    aidb_t db;
    DOCTEST_REQUIRE_MESSAGE(db.create(filename, pass) == aidb_t::opstate::ok, "create db fail");

    std::string s;
    dstring_t ds;
    for (int i = 0; i < 10; i++) {
        key = rand.next();
        ds.clear();
        ds.format("title is {}", key);
        aidb_value_t val(ds, string_view(), string_view(), string_view(), string_view());
        key = db.put(val);
        ids.emplace(key, ds.to_string());
    }

    for (auto kv : ids) {
        auto val = db.get(kv.first);
        DOCTEST_CHECK_MESSAGE(val.title == kv.second, "get record fail");
    }

    auto rk = ids.begin()->first;
    db.erase(rk);
    ids.erase(rk);

    for (auto k : db) {
        DOCTEST_CHECK_MESSAGE(ids.erase(k) == 1, "delete record fail");
    }
    DOCTEST_CHECK(ids.size() == 0);
}

